package acme.ws;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OAuthAccessServlet extends JSONServlet {
	
	private static final long serialVersionUID = 8875392317087332094L;
	
	private static String clientID;
	private static String scope;
	private static String redirectURI;
	private static String areaID = "258";
	
	@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
		clientID = request.getParameter("client_id");
		
		scope = request.getParameter("scope");
		redirectURI = request.getParameter("redirect_uri");
		if(redirectURI==null || scope==null || clientID==null)
		{
			
				throw new RuntimeException("Missing either client_id, redirect_uri, or scope");
			
		}
		
		
		
		
		
		InputStream input = getServletContext().getResourceAsStream("Login.html");
		String html= "";
		int content;
		while ((content = input.read()) != -1) {
			// convert to char and display it
			html = html + (char) content;
		}
		
		String areaID = "258";
		String appName = TestAPI.masheryAPIFetchAccessToken(OAuthAuthorizationServlet.clientID,OAuthAuthorizationServlet.clientSecret,OAuthAuthorizationServlet.redirectURI, OAuthAuthorizationServlet.authCode);
		
		String AuthCode = "12345";
		//String appName = "Jon's App";
		String redirect=redirectURI;
		html = html.replace("XRedirectX", redirect);;
		html = html.replace("XapplicationNameX", appName);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(html);
	}
	  
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
	
		
		// Login page has posted username and password.
		// Assume successful.
		// Fetch Auth Code.
		
		
		
		
		scope = req.getParameter("client_id");
		String clientSecret = req.getParameter("client_secret");
		redirectURI = req.getParameter("redirect_uri");
		String authCode = req.getParameter("code");

		String appName = TestAPI.masheryAPIFetchAccessToken(clientID,clientSecret,redirectURI, authCode);
		//String authCode = TestAPI.masheryAPIFetchAuthCode(clientID, areaID, redirectURI,scope);
		
		//resp.sendRedirect(redirectURI+"?code=" + authCode);
		//  Redirect to redirect URI with Auth code.
		
		
		

	}


	
}
